﻿﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Common;

namespace Core
{
    public class ProductRepository : RepositoryBase<Product, long>, IProductRepository
    {
        private readonly ICache _Cache;

        public ProductRepository(
            IDbContext context,
            ICache _cache)
            : base(context)
        {
            _Cache = _cache;
        }

        public IEnumerable<Product> GetProductsByCategoryId(int CategoryId)
        {
            return _Cache.Get(Settings.AllProductsKey, () =>
            {
                return DbSet.Where(p => (p.CategoryId == CategoryId && p.IsActive));
            });
        }

        public override IEnumerable<Product> GetAll()
        {
            return _Cache.Get(Settings.ProductsCategoryKey, () =>
            {
                var prodList = base.GetAll();
                prodList = prodList.Where(p => p.IsActive);
                return prodList.ToList();
            });
        }

        protected override void SaveChanges()
        {
            if (Context.ChangeTracker.HasChanges())
            {
                _Cache.Remove(Settings.AllProductsKey);
                _Cache.Remove(Settings.ProductsCategoryKey);
                Context.SaveChanges();
            }
        }
    }
}